package cn.willbj.brief.rt.util.concurrent.CompletableFuture;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 【对象方法】
 *
 * thenAcceptBoth
 * 当两个CompletionStage都执行完成后，把结果一块交给thenAcceptBoth来进行消耗
 *
 * thenAcceptBoth 和 thenCombine的区别感觉是: 一个没有返回值，一个有返回值
 *
 * 链接：https://www.jianshu.com/p/6bac52527ca4
 * @date 2020/12/1
 */
public class Demo08 {

    private static final ExecutorService es = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()*2);

    public static void main(String[] args) throws Exception {
        Demo08.test01();
    }


    /**
     * 执行顺序:
     * pool-1-thread-1 : num1
     * pool-1-thread-2 : num2
     * pool-1-thread-3 : return_value01
     * pool-1-thread-3 : return_value02
     */
    public static void test01()throws Exception{
        CompletableFuture<String> future01 = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(2000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + " : num1");
            return "return_value01";
        }, es);

        CompletableFuture<String> future02 = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(2000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + " : num2");
            return "return_value02";
        }, es);

        future01.thenAcceptBothAsync(future02, (x,y)->{
            System.out.println(Thread.currentThread().getName() + " : "+x);
            System.out.println(Thread.currentThread().getName() + " : "+y);
        }, es);
        /*future01.thenCombineAsync(future02, (x,y)->{
            System.out.println(Thread.currentThread().getName() + " : "+x);
            System.out.println(Thread.currentThread().getName() + " : "+y);
            return null;
        }, es);*/
    }

}
